//
//  BBNetWorkTool.swift
//  BaoKanSwift
//
//  Created by uncle-R on 16/6/12.
//  Copyright © 2016年 uncle-R. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class BBNetWorkTool: NSObject {

    static let shareNetworkTool = BBNetWorkTool()
    //定义一个 闭包接收返回的参数.
    // success:请求是否成功  result: 请求返回的结果 error:错误信息
    typealias ToolFinished = (success:Bool,result:JSON?,error:NSError?) -> ()
}

extension BBNetWorkTool{
    
    
    
    
    /**
     get请求
     
     - parameter URLString: URL地址
     - parameter Param:     参数.
     - parameter finished:  回调:
     */
   func get(URLString:String,Param:[String:AnyObject]?,finished:ToolFinished) {
        
        let tempString = checkURl(URLString)

    
        Alamofire.request(.GET, tempString, parameters: Param).responseJSON { (response) -> Void in
            
            if let data = response.data{
                let json = JSON(data:data)
                if json["err_msg"].string == "success"{
                    finished(success: true ,result: json,error: nil)
                }else{
                    finished(success: false, result: json, error: response.result.error)
                }
            }else{ //请求不成功.
                finished(success: false, result: nil, error: response.result.error)
            }
        }
    }
    
    func Post(URLString:String,Param:[String:AnyObject]?,finished:ToolFinished){
        
        let tempString = checkURl(URLString)
        Alamofire.request(.POST, tempString, parameters: Param).responseJSON { (response) -> Void in
            
            if let data = response.data {
    
             let json = JSON(data: data)
            
                if json["err_msg"].string == "sucess"{

                    finished(success: true,result:json,error: response.result.error)
                }else{
                    
                    finished(success: false, result: json, error: response.result.error)
                }
            }else{ //请求不成功.
                finished(success: false, result: nil, error: response.result.error)
            }
            
        }

    }
    
    func checkURl(URLString:String) -> String {
        
        var tempString = ""
        if URLString.hasPrefix("http") {
            tempString = URLString
        }else{
            tempString = "\(API_URL)\(URLString)"
        }
        
        return tempString
    }


}